import json
import time

from flask import Blueprint,send_file,jsonify,request
from application.models.users.user import User
from captcha.image import ImageCaptcha
import random,string,re,redis
from ronglian_sms_sdk import SmsSDK
from app import db
from werkzeug.security import generate_password_hash,check_password_hash
from application.tools.myredis import red
from application.tools.mjwt import myjwt

user_blue = Blueprint("userblue",__name__)


# 权限认证
# def islogin(func):
#     def wrapper():
#         print("接口执行前操作")
#         func()
#         return func
#     return wrapper()


# 测试
@user_blue.route('/test')
def test():
    id = request.args.get('id')
    return jsonify({"code":200,"id":id,'msg':'OK'})


# 生成图片验证码
@user_blue.route('/img/<uuid>')
def ImageCode(uuid):
    # 生成四位随机数
    code = ''.join(random.sample(string.digits+string.ascii_lowercase,4))
    captcha = ImageCaptcha()
    # 生成图片验证码
    imgcode = captcha.generate(code)
    # 将验证码存入redis数据库
    red.str_add(uuid,code)
    # 返回图片验证码
    return send_file(imgcode,'image/png')


# 校验图片验证码并生成手机验证码
@user_blue.route('/sms_code/<uuid>',methods=["POST"])
def sms_code(uuid):
    data = request.json
    image_code = data.get('image_code')
    mobile = data.get('mobile')

    # 校验参数是否完整
    if not all([uuid,image_code,mobile]):
        return jsonify({
            'code':400,
            'msg':'参数不完整'
        })
    image_code2 = red.str_get(uuid)
    if image_code2:
        image_code2 = image_code2
        print("我的验证码》》》》》》》",image_code)
        print('数据库验证码》》》》》》',image_code2)
    else:
        return jsonify({
            'code':400,
            'msg':'图片验证码已过期'
        })
    if image_code2.lower() != image_code.lower():
        return jsonify({
            'code':400,
            'msg':'图片验证码错误'
        })
    req = re.findall(r'^1[3-9]\d{9}$',mobile)
    if not req:
        return jsonify({
            'code':400,
            'msg':'手机号格式错误'
        })
    accId = '8a216da882f1f5940183546fdb0f119f'
    accToken = '0396f6adb55443fca4fe3bd9f4978682'
    appId = '8a216da882f1f5940183546fdbf911a6'

    sdk = SmsSDK(accId, accToken, appId)
    tid = '1'
    code = "%06d" % random.randint(0, 999999)
    # 将手机验证码存到redis中
    red.str_add(mobile,code)
    datas = (code, '6')
    resp = sdk.sendMessage(tid, mobile, datas)
    print(resp)
    return jsonify({
        'code':200,
        'msg':'短信验证码获取成功'
    })


# 注册
@user_blue.route('/login',methods=['POST'])
def register():
    # 获取前端字段
    data = request.data
    data = request.json
    mcode = data.get('code')
    mobile = data.get('mobile')
    # 根据手机号去redis获取验证码
    code = red.str_get(mobile)
    if code:
        # 验证码是否相同  # 如果不相同返回错误
        if int(code)==int(mcode):
            # 如果相同查询数据库user表
            user = User.query.filter_by(mobile=mobile).first()
            if user:
                # 删除redis中的验证码
                # red.del_str(mobile)
                pass
            else:
                u = User(mobile=mobile,nikename=mobile)
                db.session.add(u)
                db.session.commit()
            user = User.query.filter_by(mobile=mobile).first()
            # 用用户信息生成jwt token
            token = myjwt.jwt_encode(data={'data':{'uid':user.id,'exp':int(time.time())}})
            # token = str(random.randint(100,1000))
            return jsonify({'code':200,'token':token,'userid':user.id})
        else:
            return jsonify({'code':10021,'msg':'验证码错误'})



@user_blue.route('/cart',methods=['POST'])
def cart():
    pass

